#include "stdafx.h"
#include "system.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//Create a new command line process and retrive it's process exis code
DWORD System::CallNewProcess(CString strParams, bool HideWindow/* = true*/)
{
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	ZeroMemory( &si, sizeof(si) );
	if (HideWindow)
	{
		si.dwFlags = STARTF_USESHOWWINDOW;
		si.wShowWindow = SW_HIDE;
	}
	si.cb = sizeof(si);

	ZeroMemory( &pi, sizeof(pi) );

	BOOL bOK = CreateProcess(NULL, const_cast<TCHAR*>(strParams.GetBuffer()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
	ASSERT(bOK);
	WaitForSingleObject(pi.hProcess,   INFINITE);  
	DWORD dwExitCode = 0;
	GetExitCodeProcess(pi.hProcess,   &dwExitCode); 
   
	// Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );

	return dwExitCode;
}

bool System::IsExe64Bit(CString strExePath)
{
	TCHAR szPath[MAX_PATH];
	GetModuleFileName(NULL, szPath, MAX_PATH);
	CString strPath = szPath;
	int pos = strPath.ReverseFind('\\');
	CString strMbitarch = strPath.Mid(0, pos + 1) + _T("mbitarch.exe");

	CString strQuotExe = _T("\"") + strExePath + _T("\"");
	DWORD dExitCode = System::CallNewProcess(strMbitarch + " " + strQuotExe);
	if (dExitCode == 34404)
	{
		return true;
	}
	return false;	
}

CString QueryRegistryValue(HKEY hRoot, CString strSubKey, CString strValueName/*, bool b64bit = false*/)
{
	CString strValue = "";

	// Open and Query registry
	LONG lRes = -1;
	HKEY hParent; 
	REGSAM mask = KEY_QUERY_VALUE;
	//if (b64bit)
	//{
	//	mask |= KEY_WOW64_64KEY;
	//}
	//lRes = RegOpenKeyEx(hRoot, TEXT(strSubKey.GetBuffer()), 0, mask, &hParent);
	lRes = RegOpenKeyEx(hRoot, strSubKey.GetBuffer(), 0, mask, &hParent);
	if (lRes != ERROR_SUCCESS)
	{
		mask |= KEY_WOW64_64KEY;
		lRes = RegOpenKeyEx(hRoot, strSubKey.GetBuffer(), 0, mask, &hParent);
	}		
	if(ERROR_SUCCESS == lRes)
	{
		char szValue[8096] = "";
		DWORD lCount = 4096;	// God! the cout should be initliazed LARGE ENOUGH firstly!!!
		LONG lRes = RegQueryValueEx(hParent, strValueName.GetBuffer(), 0, 0, (BYTE*)szValue, &lCount);
		if (ERROR_SUCCESS == lRes)
		{
			strValue = szValue;
		}
	}

	return strValue;
}
